package com.erytech.linktalk.service.internal;

import java.sql.Timestamp;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opengoss.core.IStartable;

import com.erytech.linktalk.dao.DaoFacade;

public class MessageCleaner extends TimerTask implements IStartable {

	static final Log logger = LogFactory.getLog(MessageCleaner.class);

	static final int ONE_MINUTE = 60 * 1000;

	private DaoFacade daoFacade;

	private Timer timer = null;

	public MessageCleaner(DaoFacade daoFacade) {
		this.daoFacade = daoFacade;
	}

	public void start() throws Exception {
		if (timer != null) {
			throw new IllegalStateException();
		}
		timer = new Timer("MessageCleaner", true);
		timer.schedule(this, ONE_MINUTE, ONE_MINUTE);
	}

	public void stop() throws Exception {
		if (timer == null) {
			throw new IllegalStateException();
		}
		timer.cancel();
		timer = null;
	}

	public void run() {
		logger.debug("Clean old messages...");
		Timestamp oneMinuteAgo = new Timestamp(System.currentTimeMillis()
				- ONE_MINUTE);
		daoFacade.getMessageDao().deleteOldMessages(oneMinuteAgo);
	}

}
